package com.rmondjone.androidcamerademo

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import com.rmondjone.androidcamerademo.bean.FaceBean

/**
 * copyright：
 * @author：anthui creation date： .
 * @since: 1.0.0
 * @describe:
 */
class FaceView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {


    var bitMap: Bitmap? = null

    //图片伸缩比例
    var bitMapRate = 1f

    var rect = Rect()
    var paint = Paint(Paint.ANTI_ALIAS_FLAG)
    var textPaint = Paint(Paint.ANTI_ALIAS_FLAG)


    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
//        rect = Rect(left, top, right, bottom)

        Log.e("msg", "----------- " + left + "  " + top + "  " + right + "  " + bottom)


    }


    private fun drarText(text: String, canvas: Canvas, targetRect: RectF) {
        textPaint.textSize = 11.dp
        val testString = text
        textPaint.color = Color.WHITE
        val fontMetrics: Paint.FontMetricsInt = paint.fontMetricsInt
        val baseline = (targetRect.bottom + targetRect.top - fontMetrics.descent - fontMetrics.ascent) / 2 + 3.dp
        textPaint.textAlign = Paint.Align.CENTER
        canvas.drawText(testString, targetRect.centerX(), baseline, textPaint)
    }

    override fun draw(canvas: Canvas) {
        super.draw(canvas)

        bitMap?.let {

            bitMapRate = width * 1f / it.width
            val height = it.height * bitMapRate
            rect = Rect(0, 0, width, height.toInt())

            //回执BitMap图片
            canvas.drawBitmap(it, null, rect, paint)

            apdataBean?.list?.let {

                val leftList = it.filter { listBean ->
                    listBean.position == 1
                }
                val rightList = it.filter { listBean ->
                    listBean.position != 1
                }
                drawRectAndLine(canvas, leftList, true)
                drawRectAndLine(canvas, rightList, false)

                it.forEach { listBean ->
                    //绘制中心点位
                    if (listBean.isCheck) {
                        onCallBack?.onCallBack(listBean)
                        paint.color = Color.parseColor("#362E2B")
                    } else {
                        paint.color = Color.parseColor("#C3B294")
                    }
                    canvas.drawCircle(listBean.acupoint.pointX, listBean.acupoint.pointY, 3.dp, paint)
                    paint.color = Color.WHITE
                    canvas.drawCircle(listBean.acupoint.pointX, listBean.acupoint.pointY, 1.dp, paint)
                }


            }

        }

    }


    //左边的一个间距
    var rectLeftPadding = 25.dp

    //上下间距
    var rectTopPadding = 13.dp
    var rectWidth = 60.dp
    var rectHeight = 25.dp


    /**
     * copyright：
     * @author：anthui creation date： 2020/11/26.
     * @since: 1.0.0
     * @describe: 绘制矩形 +线条
     */
    private fun drawRectAndLine(canvas: Canvas, list: List<FaceBean.ApdataBean.ListBean>?, isLeft: Boolean) {

        if (list.isNullOrEmpty()) {
            return
        }
        //获取图片高度
        val imageHeight = rect.bottom - rect.top
        val imageWidth = rect.right - rect.left

        //需要的一个高度为
        var size = list.size
        //需要的一个高度
        val shouldHeight = (size + 1) * (rectHeight + rectTopPadding)
        //开始计算的高度
        var topStrt = (imageHeight - shouldHeight) / 2 - (rectHeight + rectTopPadding)


        var left: Float
        if (isLeft) {
            left = rectLeftPadding
        } else {
            left = imageWidth - rectLeftPadding - rectWidth
        }

        list.forEachIndexed { index, it ->

            var top = topStrt + index * (rectHeight + rectTopPadding)
            val rectF = RectF(left, top, left + rectWidth, top + rectHeight)

            if (it.isCheck) {
                paint.color = Color.parseColor("#362E2B")
            } else {
                paint.color = Color.parseColor("#C3B294")
            }
            it.rectF = rectF
            canvas.drawRoundRect(rectF, 7.dp, 7.dp, paint)

            //矩形 中间的 坐标
            var pointX = 0f
            var pointY = top + rectHeight / 2

            if (isLeft) {
                pointX = left + rectWidth
            } else {
                pointX = left
            }
            paint.strokeWidth = 1.dp
            //绘制线
            canvas.drawLine(pointX, pointY, it.acupoint.pointX, it.acupoint.pointY, paint)


            drarText(it.name, canvas, rectF)
        }
    }

    //记录当前选中的 item
    var listBean: FaceBean.ApdataBean.ListBean? = null
    override fun onTouchEvent(event: MotionEvent): Boolean {

        when (event.action) {
            //手指抬起，判断抬起的区域
            MotionEvent.ACTION_UP -> {

                apdataBean?.list?.forEach {

                    var rectF = it.rectF
                    //判断是处于该矩形之内
                    if (event.x > rectF.left && event.x < rectF.right && event.y < rectF.bottom && event.y > rectF.top) {

                        listBean?.isCheck = false
                        listBean = it
                        it.isCheck = true
                        invalidate()

                    }
                }
            }
        }
        return true
    }


    fun setImage(imagePath: String) {

        bitMap = BitmapFactory.decodeFile(imagePath)
        invalidate()
    }

    var imgDataBean: FaceBean.ImgdataBean? = null
    fun setFaceData(data: FaceBean) {
        this.imgDataBean = data.imgdata
        //获取第一个数据
        data.apdata?.firstOrNull()?.let {
            changePosition(it)
        }
    }

    private var apdataBean: FaceBean.ApdataBean? = null

    fun changePosition(apdataBean: FaceBean.ApdataBean) {
        this.apdataBean = apdataBean
        imgDataBean?.let { imageData ->
//换算一个显示的比值
            val width = imageData.width
            val realWidth = rect.right - rect.left
            //计算出 最终的一个比值
            val rate = (realWidth / width) * bitMapRate
            apdataBean.list.forEachIndexed { index, listBean ->
                if (index == 0) {
                    this.listBean = listBean
                    listBean.isCheck = true
                } else {
                    listBean.isCheck = false
                }


                listBean.acupoint.apply {
                    pointX = (x * rate).toFloat()
                    pointY = (y * rate).toFloat()
                }
            }
        }
        invalidate()
    }

    var onCallBack: OnMessageCallBack? = null

    interface OnMessageCallBack {
        fun onCallBack(content: FaceBean.ApdataBean.ListBean)

    }


}